//
//  HistoryViewController.swift
//  VO_Yuejie
//
//  Created by laichunhui on 15/11/18.
//  Copyright © 2015年 lch. All rights reserved.
//

import UIKit
import MJRefresh
import SVProgressHUD
import SnapKit

let TopHeight: CGFloat = 49

class HistoryViewController: UIViewController {
    
    var tableView = UITableView(frame: ScreenBounds)
    
    /// 主题列表视图模型
    lazy var listViewModel = TopicListViewModel()
    
    /// 顶部视图
    lazy var topView = UIImageView(image: UIImage(named: "sm_history_header"))
    
    /// 背景图
    lazy var bg = UIImageView(image: UIImage(named: "sm_timeline_default_bg"))

    // 返回按钮
    lazy var backButton: UIButton = {
        let backButton = UIButton(type: UIButtonType.Custom)
        backButton.setBackgroundImage(UIImage(named: "sm_menu_back_btn"), forState: .Normal)
        backButton.addTarget(self, action: "back2Home", forControlEvents: .TouchUpInside)
        
        return backButton
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareTableView()
        
        // 界面布局
        layoutInterface()
        
        tableView.mj_header.beginRefreshing()
    }
    
    private func prepareTableView() {
        
        view.backgroundColor = UIColor.clearColor()
        tableView.backgroundColor = UIColor.clearColor()
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        
        self.automaticallyAdjustsScrollViewInsets = true

        // 注册可重用 cell - 一个表格可以注册多个可重用 cell
        tableView.registerNib(UINib(nibName: "TopicCell", bundle: nil), forCellReuseIdentifier: TopicCellRID)
        
        tableView.contentInset = UIEdgeInsetsMake(TopHeight, 0, 0, 0)
        
        // 取消分割线
        tableView.separatorStyle = .None
        
        // 下拉刷新控件
        let vo_header = MyRefreshHeader(refreshingTarget: self, refreshingAction: "loadTopicData:")
       //vo_header.frame = CGRectMake(0, 10, ScreenWidth, 110)
        tableView.mj_header = vo_header
        
        // 上拉控件
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadTopicData:")
        tableView.mj_footer.hidden = true
        // tableView.tableFooterView = pullupView
    }
    
    func layoutInterface() {
        
        view.insertSubview(bg, atIndex: 0)
        
        view.addSubview(backButton)
        
        view.addSubview(topView)
        
        bg.frame = ScreenBounds
        
        backButton.snp_makeConstraints { (make) -> Void in
            
            make.width.height.equalTo(45)
            make.left.equalTo(self.view).offset(14)
            make.bottom.equalTo(self.view
                ).offset(-14)
        }
        
        topView.snp_makeConstraints { (make) -> Void in
            
            make.height.equalTo(TopHeight)
            make.left.right.top.equalTo(self.view)
        }
    }
    
    func back2Home() {
        
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    // MARK: - 数据加载
    func loadTopicData(headerFooterView: MJRefreshComponent) {
    
        let refreshType: RefreshType = headerFooterView is MJRefreshFooter ? .PullUp : .PullDown
        
        switch refreshType {
        case .PullUp:
            // 结束上拉刷新
            self.tableView.mj_footer.endRefreshing()
        case .PullDown:
            // 关闭下拉刷新控件
            self.tableView.mj_header.endRefreshing()
        }
        
        // 以上拉刷新控件事否动画判断是否是上拉刷新
        listViewModel.loadTopics(refreshType) { (error) -> () in
            
            switch refreshType {
            case .PullDown:
                // 结束上拉刷新
                self.tableView.mj_footer.endRefreshing()
            case .PullUp:
                // 关闭下拉刷新控件
                self.tableView.mj_header.endRefreshing()
            }
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网路不给力")
                
                return
            }
            // 已获取数据
//            print(self.listViewModel.topics)
   
            self.tableView.reloadData()
            
        }
    }
    
    deinit {
        //        for view in window.subviews {
        //
        //            if view is UIButton {
        //                view.removeFromSuperview()
        //            }
        //        }
    }
}

// MARK: - Table view data source
extension HistoryViewController: UITableViewDataSource, UITableViewDelegate {
    
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return listViewModel.topics.count
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        // 1. 取出视图模型
        let vm = listViewModel.topics[indexPath.row]
        
        // 2. 获取可重用 cell
        let cell = tableView.dequeueReusableCellWithIdentifier(TopicCellRID, forIndexPath: indexPath) as! TopicCell
        
        // 3. 设置视图模型
        cell.viewModel = vm
        
        // 4. 如果是最后一条数据，开始上拉刷新
        if indexPath.row == listViewModel.topics.count - 1 && !tableView.mj_footer.isRefreshing() {
            tableView.mj_footer.beginRefreshing()
          
            loadTopicData(tableView.mj_footer)
        }

        cell.timeView.height = indexPath.row % 2 == 0 ? 0 : 85
        return cell
    }
// MARK: - Table view delegate
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
        return listViewModel.topics[indexPath.row].rowHeight
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let vm = listViewModel.topics[indexPath.row]
        navigationController?.pushViewController(DetailViewController(topicVM: vm), animated: true)
    }
    
    /** 加载cell时的动画
        动画思路：将需要变幻的视图加到animationView：UIView中(注意：利用contenView无法实现动画，原因未知）
        利用gap（cell中心距离分界线的距离）计算相应位置的缩小比例
     */
     func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let viewHeight: CGFloat = scrollView.height + scrollView.contentInset.top
    
        for cell in self.tableView.visibleCells {
            if cell is TopicCell {
                
                let criticalY: CGFloat = cell.centerY - scrollView.contentOffset.y
                
                let gap: CGFloat = criticalY - viewHeight * 0.8
                
                var scale: CGFloat = cos(gap / (viewHeight * 0.5))
         
                if gap <= 0 {
                    scale = 1
                }
                
                UIView.animateWithDuration(0.15, delay: 0, options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.BeginFromCurrentState], animations: {() -> Void in
    
                    (cell as! TopicCell).animationView.transform = CGAffineTransformMakeScale(scale, scale)
                    
                    }, completion: nil)
                }
            
            }
        }

}
